package wei.qiang.ye.springbootdatasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootApplication
public class SpringbootDatasourceApplication implements CommandLineRunner {



    private Logger logger = LoggerFactory.getLogger(SpringbootDatasourceApplication.class);

    public static void main(String[] args) {
		SpringApplication.run(SpringbootDatasourceApplication.class, args);
	}

    /**
     * 单数据源
     */
//    @Autowired
//    private DataSource dataSource;
//    @Override
//    public void run(String... args) {
//        try (Connection conn = dataSource.getConnection()) {
//            // 这里，可以做点什么
//            logger.info("[run][获得连接：{}]", conn);
//        } catch (SQLException e) {
//            throw new RuntimeException(e);
//        }
//    }

    //@Resource 如果指定了name，则从上下文中查找名称（id）匹配的bean进行装配，找不到则抛出异常
    @Resource(name = "liughDataSource")
    private DataSource liughDataSource;

    @Resource(name = "usersDataSource")
    private DataSource usersDataSource;

    @Override
    public void run(String... args) {
        // orders 数据源
        try (Connection conn = liughDataSource.getConnection()) {
            // 这里，可以做点什么
            logger.info("[run][liughDataSource 获得连接：{}]", conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // users 数据源
        try (Connection conn = usersDataSource.getConnection()) {
            // 这里，可以做点什么
            logger.info("[run][usersDataSource 获得连接：{}]", conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
